package com.yzy.fly.config;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yzy.fly.util.DateUtil;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

//import com.fasterxml.jackson.databind.ObjectMapper;

public class GsonRedisSerializer<T> implements RedisSerializer<Object> {
     public static final Charset DEFAULT_CHARSET;
    private Class<T> type;
    private JavaType javaType;
    public GsonRedisSerializer(Class<T> type) {
        this.type = type;
        this.javaType = this.getJavaType(type);
    }

    public GsonRedisSerializer(JavaType javaType) {
        this.javaType = javaType;
    }

    public T deserialize(@Nullable byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        } else {
            try {
//                Gson gson = new GsonBuilder().create();
                Gson gson = new GsonBuilder().setDateFormat(DateUtil.DateFormatPattern.yyyy_MM_dd_HH_mm_ss).create();
                return gson.fromJson(new String(bytes, DEFAULT_CHARSET),type);
            } catch (Exception var3) {
                throw new SerializationException("Could not read JSON: " + var3.getMessage(), var3);
            }
        }
    }

    public byte[] serialize(@Nullable Object t) throws SerializationException {
        if (t == null) {
            return EMPTY_ARRAY;
        } else {
            try {
//                Gson gson = new GsonBuilder().create();
                Gson gson = new GsonBuilder().setDateFormat(DateUtil.DateFormatPattern.yyyy_MM_dd_HH_mm_ss).create();
                return gson.toJson(t).getBytes(DEFAULT_CHARSET);
            } catch (Exception var3) {
                throw new SerializationException("Could not write JSON: " + var3.getMessage(), var3);
            }
        }
    }

    protected JavaType getJavaType(Class<?> clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
    }

    static final byte[] EMPTY_ARRAY = new byte[0];

}
